package com.xunk.scene.handler.delay;

import com.xunk.common.core.domain.ControlDeviceParam;
import com.xunk.common.core.utils.SpringUtils;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.scene.domain.SceneActionEquipment;
import com.xunk.scene.domain.SceneResultAction;
import com.xunk.scene.enums.ExecutionResultEnum;
import com.xunk.scene.mapper.SceneResultActionMapper;
import com.xunk.scene.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.scene.handler.delay
 * @ClassName: SceneEquipmentDelayAction
 * @Author: luanzhiwei
 * @Description:
 * @Date: 2021/5/18 15:47
 * @Version: 1.0
 */
public class SceneDelayActionEquipment implements Runnable {
    private SceneActionEquipment action;

    public SceneDelayActionEquipment(SceneActionEquipment action) {
        this.action = action;
    }

    private DeviceService deviceService = SpringUtils.getBean(DeviceService.class);

    private SceneResultActionMapper sceneResultActionMapper = SpringUtils.getBean(SceneResultActionMapper.class);


    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        final ControlDeviceParam controlDeviceParam = new ControlDeviceParam(null, action.getDeviceSn(), action.getPropValue(), action.getDeviceProp(), null);
        final AjaxResult ajaxResult = deviceService.controlDevice(Collections.singletonList(controlDeviceParam));
        if (!ajaxResult.isSuccess()) {
            final SceneResultAction sceneResultAction = new SceneResultAction();
            sceneResultAction.setResult(ExecutionResultEnum.FAIL.getCode());
            sceneResultAction.setFailReason(ajaxResult.getMsg());
            sceneResultAction.setDeviceSn(action.getDeviceSn());
            sceneResultActionMapper.updateByDeviceSn(sceneResultAction);
        }
    }
}
